iT邦幫忙

2022 iThome 鐵人賽

DAY 17
0
自我挑戰組

Ruby OOP to Oops !n 30系列 第 17

IT 邦鐵人賽 Day 17 - Composite

  • 分享至 

  • xImage
  •  

組合模式(Composite)

目的:

將物件組織成樹狀結構、『部分-全體』層級關係,讓外界以一致性的方式對待個別物件和整體物件。

結構:

https://ithelp.ithome.com.tw/upload/images/20221002/20151094SJAIYhs7Cs.png

程式碼範例:

class Component
  # @return [Component]
  def parent
    @parent
  end

  def parent=(parent)
    @parent = parent
  end

  def add(component)
    raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
  end

  def remove(component)
    raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
  end

  def composite?
    false
  end

  def operation
    raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
  end
end


class Leaf < Component
  def operation
    'Leaf'
  end
end


class Composite < Component
  def initialize
    @children = []
  end

  def add(component)
    @children.append(component)
    component.parent = self
  end

  def remove(component)
    @children.remove(component)
    component.parent = nil
  end

  def composite?
    true
  end

  def operation
    results = []
    @children.each { |child| results.append(child.operation) }
    "Branch(#{results.join('+')})"
  end
end

def client_code(component)
  puts "RESULT: #{component.operation}"
end

def client_code2(component1, component2)
  component1.add(component2) if component1.composite?

  print "RESULT: #{component1.operation}"
end


simple = Leaf.new
puts 'Client: I\'ve got a simple component:'
client_code(simple)
puts "\n"


tree = Composite.new

branch1 = Composite.new
branch1.add(Leaf.new)
branch1.add(Leaf.new)

branch2 = Composite.new
branch2.add(Leaf.new)

tree.add(branch1)
tree.add(branch2)

puts 'Client: Now I\'ve got a composite tree:'
client_code(tree)
puts "\n"

puts 'Client: I don\'t need to check the components classes even when managing the tree:'
client_code2(tree, simple)

結果

Client: I've got a simple component:
RESULT: Leaf

Client: Now I've got a composite tree:
RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf))

Client: I don't need to check the components classes even when managing the tree:
RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf)+Leaf)

解釋

可以將整個設計概念想成是節點(Composite)與端點(Leaf),節點可以包涵端點或者節點,的是端點就不包含其他東西。而多個節點(Composite)組合,可以變成一個tree
當然也可以想成盒子(Composite),內容物則可能包含更多盒子(Composite)與產品(Leaf),而外部最大的盒子,就是一個tree

文章不定期更新!

感謝大家 如有問題,再煩請大家指教!


上一篇
IT 邦鐵人賽 Day 16 - Bridge
下一篇
IT 邦鐵人賽 Day 18-Decorator
系列文
Ruby OOP to Oops !n 3020
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Jean_HSU
iT邦新手 5 級 ‧ 2022-10-03 22:03:07

喳喳

我要留言

立即登入留言